package com.jiandan.plugin.utils

import java.security.MessageDigest

class Util {

    static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null
        }
        MessageDigest digest
        FileInputStream inputStream = null
        byte[] buffer = new byte[1024]
        int len
        try {
            digest = MessageDigest.getInstance("MD5")
            inputStream = new FileInputStream(file)
            while ((len = inputStream.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len)
            }

        } catch (Exception e) {
            e.printStackTrace()
            return null
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close()
                } catch (IOException e) {
                    e.printStackTrace()
                }
            }
        }
        return bytesToHexString(digest.digest())
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder()
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(0xFF & aByte)
            if (hex.length() == 1) {
                sb.append('0')
            }
            sb.append(hex)
        }
        return sb.toString()
    }

    static String formatFileMB(long size, int scale) {
        double fileSizeLong = size / 1048576f
        BigDecimal result = new BigDecimal(Double.toString(fileSizeLong))
        return result.setScale(scale, BigDecimal.ROUND_HALF_UP) + "MB"
    }

}
